package com.lock.api;

import com.lock.mapper.TbItemMapper;
import com.lock.mapper.TbTicketMapper;
import com.lock.pojo.TbTicket;
import com.supergo.common.pojo.TbItem;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * Created by on 2019/6/14.
 */
@RestController
public class SeckillController {

    //注入
    @Autowired
    private TbTicketMapper tbTicketMapper;

    //注入
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 需求：抢火车票
     * @return
     */
    @RequestMapping({"index","index.html","/"})
    public boolean decrstockCount(){

        Integer productId = 1;

        String key = "dec_store_lock_" + productId;
        //获取锁对象
        RLock lock = redissonClient.getLock(key);
    try {
        //加锁 操作很类似Java的ReentrantLock机制
        lock.lock(2, TimeUnit.MINUTES);

        //1、查询
        TbTicket tbTicket = tbTicketMapper.selectByPrimaryKey(productId);

        // 线程1 ， 线程2，线程3  --- 查询余票：10

        // 线程4 ，线程5 ，线程6  --- 查询余票 9

        //2、判断 如果库存为空
        if (tbTicket.getNum()==0) {
            System.out.println("票已售完!");
            return false;
        }
        //3、减票库存
        tbTicket.setNum(tbTicket.getNum()-1);

        System.out.println("已购票："+Thread.currentThread()+"::"+tbTicket.getId() +"号票");
        //4、更新库存
        tbTicketMapper.updateByPrimaryKey(tbTicket);

        } catch (Exception e) {
        //5、异常
        System.out.println(e.getMessage());
        } finally {
        //6、解锁
         lock.unlock();
        }
        return true;

        }


    /**
     * 需求：不加锁抢火车票
     * 模拟：100线程
     * @return
     */
    @RequestMapping({"decrstock","decrstock.html"})
    public boolean decrstock(){

        Integer productId = 1;
        try {
            TbTicket tbTicket = tbTicketMapper.selectByPrimaryKey(productId);
            //极限时间差情况下
            Thread.sleep(3000);

            //如果库存为空
            if (tbTicket.getNum()==0) {
                System.out.println("票已售完!");
                return false;
            }
            //减票库存
            tbTicket.setNum(tbTicket.getNum()-1);
            System.out.println("已购票："+Thread.currentThread()+"::"+tbTicket.getId() +"号票");
            System.out.println("还剩余："+tbTicket.getNum() +"张票");
            //更新库存
            tbTicketMapper.updateByPrimaryKey(tbTicket);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
        }
        return true;

    }


}
